package leetcode.editor.cn;

public class _2_AddTwoNumbers {
    public static void main(String[] args) {
        Solution solution = new _2_AddTwoNumbers().new Solution();
        ListNode l1_2 = new _2_AddTwoNumbers().new ListNode(4, null);
        ListNode l1_1 = new _2_AddTwoNumbers().new ListNode(6, l1_2);
        ListNode l1_0 = new _2_AddTwoNumbers().new ListNode(5, l1_1);


        ListNode l2_2 = new _2_AddTwoNumbers().new ListNode(3, null);
        ListNode l2_1 = new _2_AddTwoNumbers().new ListNode(4, l2_2);
        ListNode l2_0 = new _2_AddTwoNumbers().new ListNode(2, l2_1);

        final ListNode res = solution.addTwoNumbers(l1_0, l2_0);
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    //leetcode submit region begin(Prohibit modification and deletion)


    class Solution {

        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode head = null, tail = null;
            int carry = 0;
            while (l1 != null || l2 != null) {
                int n1 = l1 != null ? l1.val : 0;
                int n2 = l2 != null ? l2.val : 0;
                int sum = n1 + n2 + carry;
                carry = sum / 10;
                if (head == null) {
                    head = tail = new ListNode(sum % 10);
                } else {
                    tail.next = new ListNode(sum % 10);
                    tail = tail.next;
                }
                if (l1 != null) {
                    l1 = l1.next;
                }
                if (l2 != null) {
                    l2 = l2.next;
                }
            }
            if (carry == 1) {
                tail.next = new ListNode(1);
            }
            return head;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}